//本页面由uniapp切片工具生成，uni-app切片-可视化设计工具(一套代码编译到7个平台iOS、Android、H5、小程序)，软件下载地址：http://www.ymznkf.com/new_view_669.htm
//import app from "../../App.vue"
import {
		USER_HAS_LOGIN,
		USER_IDENTITY,
	} from "@/common/util/constants"
	
export default {
	name: 'recharge',
	data() {
		return {
			animation: '',
			animationData: {},
			vipLevelId: '', 		//会员类型ID
			money: '0.00', 			//充值金额
			payType: '0', 			//付款方式(0-微信, 1-支付宝)

			vipLevels: [], 			//会员种类
			orderInfo2: '',
			requestPaymentComplate: '',
		}
	},
	components: {

	},
	onLoad(options) {
		// 初始化一个动画
		var animation = uni.createAnimation({
			transformOrigin: "50% 0 50%",
			duration: 1000, //动画持续1秒
			timingFunction: 'linear', //linear 全程匀速运动
			delay: 200 //延迟两秒执行动画
		})
		this.animation = animation;
		this.scaleAndScale();
	},
	onShow() {
		this.validHasLoginAndIdentity()
		this.loadVipLevels()
	},
	methods: {
		//验证登录和用户身份
		validHasLoginAndIdentity(){
			this.userHasLogin = uni.getStorageSync(USER_HAS_LOGIN)
			if(this.userHasLogin!='1'){
				let app_must_permission_status = uni.getStorageSync('APP_MUST_PERMISSION_STATUS')
				uni.clearStorageSync();
				uni.setStorageSync('APP_MUST_PERMISSION_STATUS', app_must_permission_status)
				uni.redirectTo({
				    url: '/pages/login/login'
				});
				return false
			}
			this.userIdentity = uni.getStorageSync(USER_IDENTITY)
			if(this.userIdentity!='0'){
				this.$tip.toast('仅对会员开放');
				setTimeout(function() {
					uni.navigateBack({
						delta: 1
					})
				}, 500);
				return false;
			}
		},
		//会员种类-加载
		loadVipLevels() {
			uni.showLoading({
				title: '加载中...',
				mask: true,
			})
			let that = this
			that.$http.get("/viplevel/vipInfo/list", {}).then(res => {
				if (res.data.success) {
					uni.hideLoading()
					let _rv = res.data.result.records
					if (!_rv) {
						that.$tip.toast('会员充值维护中...');
						return false
					}
					for (let i = 0; i < _rv.length; i++) {
						that.vipLevels.push({
							id: _rv[i].id,
							name: _rv[i].vipName,
							price: _rv[i].vipPrice,
							expire: _rv[i].expire,
							expireDay: _rv[i].expireDay,
							isXufei: _rv[i].isXufei,
							active: false
						})
					}
					that.vipLevels = _rv
				} else {
					uni.hideLoading()
					that.$tip.cyToast('会员类型加载失败');
				}
			}).catch(e => {
				uni.hideLoading()
			});
		},
		//会员种类-选择
		choseVipLevel(item) {
			if (!item) {
				return false;
			}

			if (item.active) {
				//高亮点击了自己表示取消当前
				item.active = false
				this.vipLevelId = ''
				this.money = '0.00'
				return false;
			} else {
				//点击了其它的
				for (let i = 0; i < this.vipLevels.length; i++) {
					this.vipLevels[i].active = false;
				}
				item.active = true
				this.vipLevelId = item.id
				this.money = item.vipPrice
			}
		},
		//切换支付方式
		changePayType(type) {
			if (type == this.payType) {
				//选择了本身, 表示取消重新选择
				this.payType = ''
				return false
			}
			this.payType = type
		},
		// 定义动画内容
		scaleAndScale() {
			// 定义动画内容
			this.animation.opacity(0, 1).step() //先放大1,2倍
			this.animation.opacity(1, 0).step() //缩小至原来的大小
			// 导出动画数据传递给data层
			this.animationData = this.animation.export(); //每次执行导出动画时 会覆盖之前的动画
		},
		noscaleAndScale() {
			this.animation.scale(1, 1).step()
			this.animationData = this.animation.export()
		},
		//
		toMine(){
			/* uni.navigateBack({
				delta:1
			}) */
			this.$emit('changeTabPage', 'mine')
		},
		//提交订单
		submitOrder() {
			if (!this.vipLevelId) {
				this.$tip.toast('请选择会员类型')
				return false;
			}
			if (this.payType == '') {
				this.$tip.toast('请选择付款方式')
				return false;
			}
			
			//向本平台提交订单信息
			/*
			创建订单向后台传参:
				orderType: 订单类型(0-会员充值场景, 1-非会员按次消费服务项目)
				payType: 支付方式(0-微信, 1-支付宝)
					orderType=0时, 额外回传[vipLevelId: 会员类型ID]
					orderType=1时, 额外回传[serviceItemId: 服务项目ID]
			*/
			let _params = {
				orderType: '0',
				payType: this.payType,
				vipLevelId: this.vipLevelId
			}
			uni.showLoading({
				title: '下单中...',
				mask: true,
			})
			let that = this
			that.$http.post("/orderinfo/orders/add", _params).then(res=>{
				if(res.data.success){
					uni.hideLoading()
					let serverJsonData = res.data.result
					if(!serverJsonData){
						that.$tip.toast('下单失败,刷新重试或联系客服处理')
						return false
					}
					if (that.payType == '0') {
						//微信付款
						that.useWeiXinPay(serverJsonData)
					} else if (that.payType == '1') {
						//支付宝付款
						that.useZhiFuBaoPay(serverJsonData)
					} else {
					}
				}else{
					uni.hideLoading()
					that.$tip.toast(res.data.message);	
				}
			}).catch(err => {
				uni.hideLoading()
			});
		},

		//微信付款
		useWeiXinPay(serverJsonData) {
			if(!serverJsonData){
				this.$tip.toast('订单异常,请联系客服处理')
				return false
			}
			let _orderInfo = serverJsonData.orderInfo
			uni.showLoading({
				title: '交易处理中...',
				mask: true,
			})
			let that = this
			uni.requestPayment({
				provider: 'wxpay',
				orderInfo: _orderInfo, //订单数据
				complete: function(res){
					/*微信-付款后，返回值结构
					{
						"channel": {
							"id": "wxpay",
							"description": "微信",
							"serviceReady": true
						},
						"rawdata": "{\"_wxapi_baseresp_transaction\":\"null\",\"_wxapi_payresp_extdata\":\"null\",\"_wxapi_command_type\":\"5\",\"_wxapi_baseresp_errcode\":\"0\",\"_wxapi_baseresp_errstr\":\"null\",\"_wxapi_baseresp_openId\":\"null\",\"_wxapi_payresp_returnkey\":\"\",\"_wxapi_payresp_prepayid\":\"wx1515247182706230d4cdfde2255490000\"}",
						"errMsg": "requestPayment:ok"
					}
					*/
					uni.hideLoading()
					let commonErrorTip = '付款失败'
					if(!res){
						that.$tip.toast(commonErrorTip)
						return false
					}
					if(!res.rawdata){
						that.$tip.toast(commonErrorTip)
						return false
					}
					let _wxAppPay = res.rawdata
					
					//将JSON字符串转为JSON对象
					_wxAppPay = JSON.parse(_wxAppPay)
					
					//判定支付成功或失败
					let _errMsg = res.errMsg.toLowerCase().trim()
					let _wxapi_baseresp_errcode = _wxAppPay._wxapi_baseresp_errcode.toLowerCase().trim()
					let _wxapi_baseresp_errstr = _wxAppPay._wxapi_baseresp_errstr.toLowerCase().trim()
					/* console.log('_errMsg = ', _errMsg)
					console.log('_wxapi_baseresp_errcode = ', _wxapi_baseresp_errcode)
					console.log('_wxapi_baseresp_errstr = ', _wxapi_baseresp_errstr) */
					if(_errMsg=='requestpayment:ok' && _wxapi_baseresp_errcode=='0' && _wxapi_baseresp_errstr=='null'){
						that.vipLevelId = ''
						that.money = '0.00'
						that.$tip.success('充值成功')
						setTimeout(function() {
							uni.navigateBack({
								delta: 1
							})
						}, 500);
					}else{
						that.$tip.toast(commonErrorTip)
					}
				}
			});
		},

		//支付宝付款
		useZhiFuBaoPay(serverJsonData) {
			if(!serverJsonData){
				this.$tip.toast('订单异常,请联系客服处理')
				return false
			}
			
			let _orderInfo = serverJsonData.orderInfo
			uni.showLoading({
				title: '交易处理中...',
				mask: true,
			})
			let that = this
			uni.requestPayment({
				provider: 'alipay',
				orderInfo: _orderInfo, //订单数据
				complete: function(res){
					/*支付宝-付款后，返回值结构
					{
						"channel": {
							"id": "alipay",
							"description": "支付宝",
							"serviceReady": true
						},
						"description": "",
						"rawdata": "{\"resultStatus\":\"9000\",\"memo\":\"\",\"result\":\"{\\\"alipay_trade_app_pay_response\\\":{\\\"code\\\":\\\"10000\\\",\\\"msg\\\":\\\"Success\\\",\\\"app_id\\\":\\\"2021003112633772\\\",\\\"auth_app_id\\\":\\\"2021003112633772\\\",\\\"charset\\\":\\\"UTF-8\\\",\\\"timestamp\\\":\\\"2022-01-13 08:58:09\\\",\\\"out_trade_no\\\":\\\"2022011308520492641599645909\\\",\\\"total_amount\\\":\\\"0.02\\\",\\\"trade_no\\\":\\\"2022011322001448431400722416\\\",\\\"seller_id\\\":\\\"2088512496097221\\\"},\\\"sign\\\":\\\"dscyx0BFKuZ0FTaAmpf+qj1kJob7JP4Nz43qAPrInGVJf0KcTzL7I2w\\/PSEBvUr37ELcD21ldeV073RUV+EOLC3Sp3goNVpQ6fXmZ8z085TyGAOdkRm6XkMsajTuCxY7QQVWuDafFEy6qnYmPUcJKTYLPkuWzrQ54L0WPbF2jR2CUTBFhzk6MmDfsjhJayMk7oG4nDFOOkp5RMpFTwtwrCR8XXtP9TxGFXMmWqfUHTYfchQVid6\\/MCdKDedn00y5OjZ2MdwfxnsmjEnTTvd+94Ci7dKSoXsA2kXxwKoGYw6Dfpa7XWxM0dzFzasDy2KxHecY0J1F2m6eNcHZTFJBqw==\\\",\\\"sign_type\\\":\\\"RSA2\\\"}};extendInfo={{\\\"doNotExit\\\":true,\\\"isDisplayResult\\\":true,\\\"tradeNo\\\":\\\"2022011322001448431400722416\\\"}\"}",
						"errMsg": "requestPayment:ok"
					}
					*/
					uni.hideLoading()
					let commonErrorTip = '付款失败'
					if(!res){
						that.$tip.toast(commonErrorTip)
						return false
					}
					if(!res.rawdata){
						that.$tip.toast(commonErrorTip)
						return false
					}
					let _rawdata = res.rawdata
					
					//定位到alipay_trade_app_pay_response位置
					let _aliAppPay = _rawdata.substring(_rawdata.indexOf('alipay_trade_app_pay_response'))
					
					//取alipay_trade_app_pay_response后的{}内键值对
					_aliAppPay = _aliAppPay.substring(_aliAppPay.indexOf('{'), _aliAppPay.indexOf('}')+1)
					
					//将字符串进行正则表达式替换，将所有的[\"]替换成["]
					_aliAppPay = _aliAppPay.replace(/\\\"/g, "\"")
					
					//将JSON字符串转为JSON对象
					_aliAppPay = JSON.parse(_aliAppPay)
					
					//判定支付成功或失败
					let _errMsg = res.errMsg.toLowerCase().trim()
					let _code = _aliAppPay.code.toLowerCase().trim()
					let _msg = _aliAppPay.msg.toLowerCase().trim()
					
					if(_errMsg=='requestpayment:ok' && _code=='10000' && _msg=='success'){
						that.vipLevelId = ''
						that.money = '0.00'
						that.$tip.success('充值成功')
						setTimeout(function() {
							uni.navigateBack({
								delta: 1
							})
						}, 500);
					}else{
						that.$tip.toast(commonErrorTip)
					}
				}
			});
		},

	}
}
